package com.bkhech.spring.security.example.controller;

import com.bkhech.spring.security.example.mvc.RequestKey2CamelCase;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.io.IOException;
import java.util.stream.Collectors;

/**
 * @author guowm
 * @date 2023/1/10
 */
@RestController
public class DemoController {

    @Data
    public static class DemoVo {
        @JsonProperty("user_name")
        @NotEmpty(message = "用户名不能为空")
        private String name;
        private String password;
    }

    @PostMapping("/hello")
    public String hello(@Valid @RequestKey2CamelCase DemoVo param, BindingResult bindingResult) throws IOException {
        if (bindingResult.hasFieldErrors()) {
            final String bindingErrorMessage = bindingResult.getFieldErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
            return bindingErrorMessage;
        }
        return param + ", hello";
    }

    @PostMapping("/demo")
    public String demo(String param) {
        return param + ", demo";
    }

}
